//
//  AudioPlayViewController.m
//  MIDI
//
//  Created by 王禹丞 on 15/11/19.
//  Copyright © 2015年 QXSX. All rights reserved.
//

#import "AudioPlayViewController.h"
#import "UIViewController+Create.h"
#import "UIViewController+NavItem.h"
#import "AudioImageTableViewCell.h"
#import "AudioControlTableViewCell.h"
#import "AudioContentTableViewCell.h"
#import "GradingTestSongDetailModel.h"
#import "NSString+Hash.h"
#import "FileDownloader.h"
#import "AppConfig.h"
#import "MBProgressHUD+YC.h"
#import "UMSocial.h"
#import "AppDelegate.h"
#import "YCAudioPlayer.h"

@interface AudioPlayViewController ()<UITableViewDataSource,UITableViewDelegate,AudioContentTableViewCellDelegate,UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong,nonatomic) FileDownloader * fileDownloader;

@property (strong,nonatomic) UIProgressView * downLoadProgress;

@property (strong,nonatomic) UIView * darkView;

@property (strong,nonatomic) UIView * downLoadView;

@property (strong,nonatomic) UILabel *downLoadLabel;

@end

@implementation AudioPlayViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    self.tableView.delegate =self;
    
    self.tableView.dataSource = self;
    
    [self checkIsMp3IsDownload];
    
    [self configNavigationItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shareToWechat) name:@"shareToWeChat" object:nil];
    


}

- (void)shareToWechat{
    
    [UMSocialData defaultData].extConfig.wechatSessionData.title = @"迷笛考级曲";
    
    [UMSocialData defaultData].extConfig.wechatSessionData.url = _songmodel.song_url;
    
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = @"迷笛考级曲";
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:UmengAppkey                                      shareText:@"迷笛考级曲"
                                     shareImage:[UIImage imageNamed:@"bg_login_logo"]
                                shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline]
                                       delegate:self];
    
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{


    return 3;


}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == 0) {
     
        return 250;
    }

    if (indexPath.row == 1) {
        
        return 41;
        
    }
    
    if (indexPath.row == 2) {
        
        return  300;
    }

    return 100;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.row == 0) {
        
        AudioImageTableViewCell * cell = [AudioImageTableViewCell cellWithTableView:tableView];
        
        cell.songModel = _songmodel;
        
        return cell;
    }
    
    if (indexPath.row == 1) {
        
        AudioControlTableViewCell *cell = [AudioControlTableViewCell cellWithTableView:tableView];
        
        cell.songModel = _songmodel;
        
        return cell;
    }
    
    if (indexPath.row == 2) {
        
         AudioContentTableViewCell *cell = [AudioContentTableViewCell cellWithTableView:tableView];
        
        cell.delegate = self;
        
        cell.songModel = _songmodel;
        
        return cell;
    }
    
    return nil;
}
-(void)configNavigationItem
{
    self.navigationItem.title = self.songmodel.song_name;
   
    [self.navigationController.navigationBar setTranslucent:NO];
    
    [self.navigationController.navigationBar
     setBackgroundImage:[UIImage imageNamed:@"bg_login_statue_bar"]
     forBarMetrics:UIBarMetricsDefault];
    
    //status bar的字体为白色
    //导航栏的背景色是黑色
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],NSFontAttributeName,nil]];
    
    [self configNavigationBackAction:^{
        
        
//        NSNotification *notification =[NSNotification notificationWithName:@"stopMusic" object:nil userInfo:nil];
//        
//        [[NSNotificationCenter defaultCenter] postNotification:notification];
        
        if ([YCAudioPlayer sharedYCAudioPlayer].player.state != STKAudioPlayerStatePaused) {
           
            [[YCAudioPlayer sharedYCAudioPlayer].player stop];
        
        }else {
        
            // 为了掩饰AudioPlayer的bug.....
            
            [[YCAudioPlayer sharedYCAudioPlayer].player resume];
        
              [[YCAudioPlayer sharedYCAudioPlayer].player stop];
            
        }
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

-(void)useMethodToFindBlackLineAndHind
{
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    blackLineImageView.hidden = YES;
}


- (void)checkIsMp3IsDownload{

    
    NSString *fileName = [NSString stringWithFormat:@"%@.mp3", [self.songmodel.song_name md5String]];
    
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    
    NSString *filepath = [caches stringByAppendingPathComponent:fileName];
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    if ([mgr fileExistsAtPath:filepath]) {
        
        _songmodel.isDownLoad = YES;
        
        _songmodel.song_url = filepath;
        
        [self.tableView reloadData];
    }

}


- (FileDownloader *)fileDownloader{
    
    if (!_fileDownloader) {
        
        _fileDownloader = [[FileDownloader alloc]init];
        
        _fileDownloader.url = _songmodel.song_url;
        
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        
    
        NSString *fileName = [NSString stringWithFormat:@"%@.mp3", [self.songmodel.song_name md5String]];
        
        NSString *filepath = [caches stringByAppendingPathComponent:fileName];
        
        _fileDownloader.destPath = filepath;
        
        
        
        __weak typeof(self) vc = self;
        
        _fileDownloader.progressHandler = ^(double progress){
            
           
            vc.downLoadProgress.progress = progress;
            
        };
     
        _fileDownloader.completionHandler = ^{
            
            [MBProgressHUD showSuccess:@"下载成功"];
            
            [vc.darkView removeFromSuperview];
            
            [vc.downLoadView removeFromSuperview];
            
           // [vc writeToPlist:filepath];
            
            NSNotification *notification =[NSNotification notificationWithName:@"isFinishDownLoad" object:nil userInfo:nil];
            
            [[NSNotificationCenter defaultCenter] postNotification:notification];
            

        };
        
        
        _fileDownloader.failureHandler = ^(NSError *error){
            
            
            
            
        };
        
    }
    
    return _fileDownloader;
    
}

- (void)downLoadBtnOnClick{

    [self toDownload];
}


- (void)configDownloadView{
    
    
    _darkView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWindowWidth, kWindowHeight)];
    
    _darkView.backgroundColor = [UIColor blackColor];
    
    _darkView.alpha = 0.4;
    
    [self.view addSubview:_darkView];
    
    
    _downLoadView = [[UIView alloc]initWithFrame:CGRectMake(40, kWindowHeight * 0.5 - 60 , kWindowWidth - 80, 100)];
    
    [self.downLoadView.layer setCornerRadius:8.0];
    
    [self.downLoadView.layer setMasksToBounds:YES];
    
    _downLoadView.backgroundColor = [UIColor whiteColor];
    
    _downLoadProgress = [[UIProgressView alloc]initWithFrame:CGRectMake(20, 70, _downLoadView.frame.size.width - 40
                                                                        , 10)];
    
    _downLoadLabel = [[UILabel alloc]initWithFrame:CGRectMake(_downLoadView.center.x - 80, 20, 70, 10)];
    
    _downLoadLabel.font = [UIFont boldSystemFontOfSize:14];
    
    _downLoadLabel.textAlignment = NSTextAlignmentCenter;
    
    _downLoadLabel.text = @"正在下载";
    
    
    _downLoadLabel.textColor = [UIColor blackColor];
    
    _downLoadProgress.backgroundColor = [UIColor redColor];
    
    [_downLoadView addSubview:_downLoadProgress];
    
    [_downLoadView addSubview:_downLoadLabel];
    
    [self.view addSubview:_downLoadView];
    
    
}


- (void)toDownload{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"下载歌曲" message:@"是否选择将歌曲下载到本地" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
  
    [alert addButtonWithTitle:@"确定"];
  
    [alert show];


}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex == 1) {
        
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        
        
        NSString *fileName = [NSString stringWithFormat:@"%@.mp3", [self.songmodel.song_name md5String]];
        
        NSString *filepath = [caches stringByAppendingPathComponent:fileName];
        
        [self writeToPlist:filepath];
        
        [self configDownloadView];
        
        [self.fileDownloader start];
       
    }

}

- (void)writeToPlist:(NSString *)filepath {

    
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    
    NSString *plistName = @"download.plist";
    
    NSString *plistpath = [caches stringByAppendingPathComponent:plistName];
    
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    
    dict[@"song_url"] = filepath;
    
    dict[@"id"] = _songmodel.id;
    
    dict[@"cover_img"] = _songmodel.cover_img;
    
    dict[@"song_name"]  = _songmodel.song_name;
    
    dict[@"song_brief"] = _songmodel.song_brief;

    dict[@"major_id"]= _songmodel.major_id;
    
    dict[@"grade_num"] = _songmodel.grade_num;
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:plistpath]) {
        
        NSMutableArray * array = [NSMutableArray arrayWithObject:dict];
        
        
        
        [array writeToFile:plistpath atomically:YES];
        
    }
    
    else
    
    {
        NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:plistpath];
       
        [array addObject:dict];
        
        [array writeToFile:plistpath atomically:YES];

    }
    

    
    
}

@end
